import * as Cesium from 'cesium';
import * as Libora from '../../public/libora/index.js'
import { WaterPrimitive } from './WaterPrimitive.js';

// https://www.liaomz.top/2022/07/27/cesium-zhong-shi-xian-shui-mian-fan-she/

(window).Cesium = Cesium;
(window).Libora = Libora;

// 后处理方案-失败
const InvertedSceneFS = `
#extension GL_OES_standard_derivatives : enable
uniform sampler2D colorTexture;
uniform sampler2D depthTexture;
in vec2 v_textureCoordinates;
vec4 toEye(in vec2 uv, in float depth) {
  vec2 xy = vec2((uv.x * 2.0 - 1.0), (uv.y * 2.0 - 1.0));
  vec4 posInCamera = czm_inverseProjection * vec4(xy, depth, 1.0);
  posInCamera = posInCamera / posInCamera.w;
  return posInCamera;
}
float getDepth(in vec4 depth) {
  float z_window = czm_unpackDepth(depth);
  z_window = czm_reverseLogDepth(z_window);
  float n_range = czm_depthRange.near;
  float f_range = czm_depthRange.far;
  return (2.0 * z_window - n_range - f_range) / (f_range - n_range);
}
vec3 guussColor(vec2 uv) {
  vec2 pixelSize = 1.0 / czm_viewport.zw;
  float dx0 = -pixelSize.x;
  float dy0 = -pixelSize.y;
  float dx1 = pixelSize.x;
  float dy1 = pixelSize.y;
  vec4 gc = (texture(colorTexture, uv) +
    texture(colorTexture, uv + vec2(dx0, dy0)) +
    texture(colorTexture, uv + vec2(0.0, dy0)) +
    texture(colorTexture, uv + vec2(dx1, dy0)) +
    texture(colorTexture, uv + vec2(dx0, 0.0)) +
    texture(colorTexture, uv + vec2(dx1, 0.0)) +
    texture(colorTexture, uv + vec2(dx0, dy1)) +
    texture(colorTexture, uv + vec2(0.0, dy1)) +
    texture(colorTexture, uv + vec2(dx1, dy1))) * (1.0 / 9.0);
  return gc.rgb;
}
void main() {
    // mat4 dither = mat4(
    //     0,       0.5,    0.125,  0.625,
    //     0.75,    0.25,   0.875,  0.375,
    //     0.1875,  0.6875, 0.0625, 0.5625,
    //     0.9375,  0.4375, 0.8125, 0.3125
    // );
    // int sampleCoordX = int(mod((gl_FragCoord.x * v_textureCoordinates.x),4.0));
    // int sampleCoordY = int(mod((gl_FragCoord.y * v_textureCoordinates.y),4.0));
  float offset = 0.0;

  vec4 color = texture(colorTexture, v_textureCoordinates);
  vec4 currD = texture(depthTexture, v_textureCoordinates);
    // out_FragColor = currD;
    // return;
  if(currD.r >= 1.0) {
    out_FragColor = color;
    return;
  }
  float depth = getDepth(currD);
    // out_FragColor = vec4(depth,0.0,0.0,1.0);
    // return;

  vec4 positionEC = toEye(v_textureCoordinates, depth);
  vec3 dx = dFdx(positionEC.xyz);
  vec3 dy = dFdy(positionEC.xyz);
  vec3 normal = normalize(cross(dx, dy));

  vec4 positionWC = normalize(czm_inverseView * positionEC);
  vec3 normalWC = normalize(czm_inverseViewRotation * normal);
  float fotNumWC = dot(positionWC.xyz, normalWC);
  if(fotNumWC <= 0.5) {
    out_FragColor = color;
    return;
  }

    // float dotNum = dot(normal,vec3(0.0,1.0,0.0));
    // out_FragColor = mix(color,vec4(1.0),dotNum*0.8);
    // return;

  vec3 viewDir = normalize(positionEC.xyz);
  vec3 reflectDir = reflect(viewDir, normal);
    // vec3 viewReflectDir = czm_viewRotation * reflectDir;
  vec3 viewReflectDir = reflectDir;

  float step = 0.05;
  int stepNum = int(20.0 / step);
  vec3 pos;
  vec3 albedo;
  bool jd = false;
  for(float i = 1.0; i <= 400.0; i+=1.0) {
    float delta = step * i + offset;
    pos = positionEC.xyz + viewReflectDir * delta;
    float d = -pos.z;

    vec4 tmp = czm_projection * vec4(pos, 1.0);
    vec3 screenPos = tmp.xyz / tmp.w;
    vec2 uv = vec2(screenPos.x, screenPos.y) * 0.5 + vec2(0.5, 0.5);

    if(uv.x > 0.0 && uv.x < 1.0 && uv.y > 0.0 && uv.y < 1.0) {
      float dd = getDepth(texture(depthTexture, uv));
      vec4 jzc = toEye(uv, dd);
      dd = -jzc.z;
      if(d > dd) {
        if(abs(abs(d) - abs(dd)) <= step) {
          jd = true;
                    // albedo = texture(colorTexture, uv).rgb;
          albedo = guussColor(uv);
        }
        break;
      }
    }
  }
  if(jd) {
    out_FragColor = vec4(mix(color.xyz, albedo, 0.5), 1.0);
  } else {
    out_FragColor = color;
  }
  // out_FragColor = vec4(1., 0., 0., 1.);
}
`

export default class Demo {
  constructor() {
    const viewer = Libora.getViewer({
      // imageryProvider: false
    });

    const tileset = viewer.scene.primitives.add(
      new Cesium.Cesium3DTileset({
        url: 'http://earthsdk.com/v/last/Apps/assets/dayanta/tileset.json'
        // url: 'https://www.liaomz.top/tiles/40866/tileset.json',
      })
    );

    // * 监测鼠标左击事件
    let drawHandler = new Cesium.ScreenSpaceEventHandler(
      viewer.scene.canvas
    );
    const arr = [];
    drawHandler.setInputAction(event => {
      let position = event.position;
      const cartesian = Libora.ClickHelper.getPickPosition(viewer.scene, position)
      if (!Cesium.defined(cartesian)) return;
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      arr.push(cartographic.longitude)
      arr.push(cartographic.latitude)
      arr.push(cartographic.height)

      console.error(arr);

    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    const arr2 = [
      1.9016692754767204,
      0.5972790239304149,
      -0.004121904995321537,

      1.9016686669527567,
      0.5972095338878505,
      6.982479848701037,

      1.9017297006625915,
      0.5972100008517349,
      0.3215844913677996,

      1.90173103562084,
      0.5972790954686791, -0.004394639263513932]

    const positions = []
    const positions2 = [];
    for (let i = 0; i < arr2.length ; i += 3) {
      positions.push(new Cesium.Cartographic(arr2[i + 0], arr2[i + 1], arr2[i + 2]))
      positions2.push(Cesium.Cartesian3.fromRadians(arr2[i + 0], arr2[i + 1]))
    }

    new WaterPrimitive({
      scene: viewer.scene,
      positions: positions,
      height: 7,
      rippleSize: 100,
      waterColor: Cesium.Color.fromCssColorString("#256dcf").withAlpha
(0.5)
    });

    tileset.readyPromise.then(function (tileset) {

      var heightOffset = -420.0;
      //计算tileset的绑定范围
      var boundingSphere = tileset.boundingSphere;

      //计算中心点位置
      var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);

      viewer.zoomTo(tileset);
      // viewer.camera.flyToBoundingSphere(boundingSphere,
      //   {
      //     offset: new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-90), 0),
      //     duration: 0,
      //   },
      // );

      //计算中心点位置的地表坐标
      var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);

      //偏移后的坐标
      var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);

      var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
      //tileset.modelMatrix转换
      tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

    })


    setInterval(() => {
      viewer.scene.requestRender()
    }, 10);
  }

}
